package cc.autoapi.pucong.auto.flow.provider.api.manager;


import cc.autoapi.pucong.auto.flow.core.flow.execNode.entity.log.LogNodeHandlerMsgDto;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.eventBus.ISubscriberAbstract;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.LogLevelTypeEnum;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.MsgTypeEnum;
import cc.autoapi.pucong.auto.flow.core.flow.execNode.selfenum.RunStatusEnum;
import cc.autoapi.pucong.auto.flow.persistence.repository.log.ApiInstanceNodeService;
import cc.autoapi.pucong.auto.flow.provider.log.manager.LogManager;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: cong.pu
 * @create: 2024-10-08 09:31
 **/
@Service
@Slf4j
public class ApiNodeLogHandler extends ISubscriberAbstract<LogNodeHandlerMsgDto> {

    @Resource
    private ApiInstanceNodeService apiInstanceNodeService;

    @Resource
    private LogManager logManager;

    private final Lock lock = new ReentrantLock(true);

    @Override
    public String getMessageType() {
        return MsgTypeEnum.LOG_MSG.getType();
    }

    @Override
    public void receiveMessage(LogNodeHandlerMsgDto message) {
        log.debug("节点日志打印：" + JSON.toJSONString(message, JSONWriter.Feature.PrettyFormat));
        RunStatusEnum runStatus = message.getRunStatus();
        // 使用公平锁
        try {
            lock.lock();
            apiInstanceNodeService.updateNodeStatus(message.getApiId(), message.getInstanceId(), message.getNodeId(), message.getInstanceNodeId(), runStatus, message.getCreateTime());
        } finally {
            lock.unlock();
        }
        if (runStatus != null) {
            if (runStatus == RunStatusEnum.执行中) {
                logManager.appendLog(LogLevelTypeEnum.INFO, message.getInstanceId(), message.getInstanceNodeId(), "开始执行");
            } else if (runStatus == RunStatusEnum.执行成功) {
                logManager.appendLog(LogLevelTypeEnum.INFO, message.getInstanceId(), message.getInstanceNodeId(), "执行成功");
            } else if (runStatus == RunStatusEnum.执行失败) {
                logManager.appendLog(LogLevelTypeEnum.INFO, message.getInstanceId(), message.getInstanceNodeId(), "执行失败");
            } else if (runStatus == RunStatusEnum.已跳过) {
                logManager.appendLog(LogLevelTypeEnum.INFO, message.getInstanceId(), message.getInstanceNodeId(), "跳过执行");
            }
        }
        LogLevelTypeEnum logLevel = message.getLogLevel();
        if (logLevel != null) {
            // 插入执行日志
            logManager.appendLog(logLevel, message.getInstanceId(), message.getNodeId(), message.getLogContent());
        }
    }
}
